package com.cneport.transfer.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.util.FileCopyUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public abstract class XmlParseUtil {
	public static final String ENCODING = "UTF-8";
	public static Document stringToDoc(String xmlStr) throws Exception {
		StringReader reader = new StringReader(xmlStr);
		return ReaderToDoc(reader);
	}
	
	private static Document ReaderToDoc(Reader  reader) throws Exception{
		InputSource is = new InputSource(reader);
		DocumentBuilderFactory factory = DocumentBuilderFactory
				.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder;
		builder = factory.newDocumentBuilder();
		Document doc = builder.parse(is);
		return doc;
	}
	
	public static Document FileToDoc(File file) throws Exception{
		InputStreamReader reader = new InputStreamReader(new FileInputStream(file),ENCODING);
		return ReaderToDoc(reader);
	}
	
	
	public static String ReadFromInputStream(File file) throws Exception{
		InputStreamReader reader = new InputStreamReader(new FileInputStream(file),ENCODING);
		return FileCopyUtils.copyToString(reader);
	}
	
	public static String ReadFromInputStream(InputStream is) throws Exception{
		InputStreamReader reader = new InputStreamReader(is);
		return FileCopyUtils.copyToString(reader);
	}
	
}
